package com.im.app.manager;

import com.im.app.model.ChatLogs;
import org.jim.core.ImPacket;
import org.jim.core.config.ImConfig;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.server.JimServerAPI;
import org.jim.server.config.ImServerConfig;
import org.jim.server.util.ChatKit;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatLogManager {


    private static ChatLogManager manager;

    public ChatLogManager(){

    }

    public Map<String, List<ChatLogs>> groupChatLogs = new HashMap<>();

    public static ChatLogManager getManager(){
        if(manager == null){
            synchronized (ChatLogManager.class){
                if(manager == null){
                    manager = new ChatLogManager();
                }
            }
        }
        return manager;
    }

    public void cacheChatLogsConversations(String key,List<ChatLogs> chatLogs){
        groupChatLogs.put(key,chatLogs);
    }

    public List<ChatLogs> getChatLogsConversations(String key){
        return groupChatLogs.get(key);
    }


    /**
     * 会话已读
     * */
    public static void sendChatLogIsRead(String id, String fromUserId){
        ImServerConfig imServerConfig = ImConfig.Global.get();
        boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
        if(ChatKit.isOnline(fromUserId,isStore)){
            ImPacket imPacket = new ImPacket(Command.COMMAND_CONVERSATION_READ_RESP,new RespBody(Command.COMMAND_CONVERSATION_READ_RESP,id).toByte());
            JimServerAPI.sendToUser(fromUserId,imPacket);
        }
    }

    /**
     * 会话已读
     * */
    public static void sendMessageReadResp(String id, String fromUserId){
        ImServerConfig imServerConfig = ImConfig.Global.get();
        boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
        if(ChatKit.isOnline(fromUserId,isStore)){
            ImPacket imPacket = new ImPacket(Command.COMMAND_MESSAGE_READ_RESP,new RespBody(Command.COMMAND_MESSAGE_READ_RESP,id).toByte());
            JimServerAPI.sendToUser(fromUserId,imPacket);
        }
    }

    public static void sendChatLogRevokeC2C(ChatLogs chatLogs){
        ImServerConfig imServerConfig = ImConfig.Global.get();
        boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
        if(ChatKit.isOnline(chatLogs.getRecvId(),isStore)){
            ImPacket imPacket = new ImPacket(Command.COMMAND_REVOKE_CHATLOGS_RESP,new RespBody(Command.COMMAND_REVOKE_CHATLOGS_RESP,chatLogs).toByte());
            JimServerAPI.sendToUser(chatLogs.getRecvId(),imPacket);
        }
    }
}
